import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'

import Login from '../views/Login.vue'
import Cart from '../views/Cart.vue'

import History from '@/utils/history'

Vue.use(VueRouter)
Vue.use(History)

//为页头创建一个方法goBack，用于返回上一页
//// 实例化之前，扩展Router
VueRouter.prototype.goBack = function () {  
  this.isBack = true
  this.back()
}

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/Cart',
    name: 'cart',
    component: Cart
  },
  {
    path: '/about',
    name: 'about',
    meta: {
      auth: true   //标记需要登录才能访问
    },
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  if(to.meta.auth){    //检查目标路由是否需要认证
    const token = localStorage.getItem('token')   //获取本地存储的token
    if(token){    //token存在时的处理
      next()
    }else{       //token不存在时的处理
      next({
        path: '/login',   //跳转到登录页面
        query: {redirect: to.fullPath}  //将目标路由的完整路径作为参数传递给登录页面，以便登录成功后跳转回目标路由不需要再次点击about
      })
    }
  }else{     //不需要认证的路由
    next()
  }
})

// afterEach记录历史记录，并设置路由的过渡效果
router.afterEach((to) => {
  if (router.isBack) {   //判断是否是返回操作
    //后退
    History.pop()   //如果是返回操作，则从历史记录中删除当前路由
    router.isBack = false
    router.transitionName = 'route-back'
  } else {
    History.push(to.path)   //如果不是返回操作，则将当前路由的路径添加到历史记录中
    router.transitionName = 'route-forward'
  }
})

export default router
